'use strict';

const Controller = require('../core/base_controller');

class Api extends Controller {


	async getSQL (service) {
		const { app, ctx } = this;

		let sqlinfo = await app.redis.get('system').hget('dlq_sql', service);

		console.log('sqlinfo');
		console.log(sqlinfo);

		if(sqlinfo == null){
			sqlinfo = await ctx.service.database.getApi(service);
		}
		sqlinfo = JSON.parse(sqlinfo);

		return sqlinfo;
	}

	//列表
	async index () {
		const { app, ctx } = this;
		const { service, ...para } = this.ctx.query;
		console.log(service);

		const sqlinfo = await this.getSQL(service);

		const result = await ctx.service.api.list(sqlinfo, para);
		this.success(result);
	}

	//更新
	async update () {
		const { ctx } = this;
		const { service, ...para } = ctx.request.body;

		const sqlinfo = await this.getSQL(service);

		const result = await ctx.service.api.update({
			...para,
			id : ctx.params.id,
		}, sqlinfo);

		this.success(result);
	}

	//创建
	async create () {
		const { ctx } = this;
		const { service, ...para } = ctx.request.body;

		const sqlinfo = await this.getSQL(service);

		const result = await ctx.service.api.update({
			...para,
		}, sqlinfo);

		this.success(result);
	}

	//删除
	async destroy () {
		const { ctx } = this;
		const { service } = ctx.request.body;

		const sqlinfo = await this.getSQL(service);

		const ids = ctx.params.id.split(',');
		let result = null;
		ids.forEach(async id => {
			if(id != ''){
				result = await ctx.service.api.update({
					id,
					del_flag : '1',
				}, sqlinfo);
			}
		});

		this.success(result);
	}

	//详情
	async show () {
		const { ctx } = this;
		const { service } = this.ctx.query;

		console.log(ctx.params.id);

		const sqlinfo = await this.getSQL(service);

		const result = await ctx.service.api.info(sqlinfo, ctx.params.id);
		this.success(result);
	}
}

module.exports = Api;
